package user_assets

import (
	"context"
	"errors"

	"gitee.com/liuxuezhan/ar-platform/base-common/headInfo"
	"github.com/jinzhu/copier"

	"gitee.com/liuxuezhan/ar-platform/rpc-client/assetsClient/rpc"

	"gitee.com/liuxuezhan/ar-platform/assets-api/internal/svc"
	"gitee.com/liuxuezhan/ar-platform/assets-api/internal/types"
	"github.com/zeromicro/go-zero/core/logx"
)

type UserBankInfoLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// user-assets
func NewUserBankInfoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserBankInfoLogic {
	return &UserBankInfoLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserBankInfoLogic) UserBankInfo() (resp *types.UserBankInfoResponse, err error) {
	request := rpc.UserBankInfoRequest{}
	copier.Copy(&request, &types.UserBankInfoRequest{})
	request.UserId = headInfo.GetTokenUid(l.ctx)
	if request.UserId == 0 {
		return &types.UserBankInfoResponse{
			UserBankInfo: []*types.UserBankInfo{},
		}, errors.New("user is not exist")
	}
	info, err := l.svcCtx.AssetsRpc.UserChannel.UserBankInfo(l.ctx, &request)
	var infos []*types.UserBankInfo

	if err != nil {
		return &types.UserBankInfoResponse{
			UserBankInfo: infos,
		}, err
	}
	if len(info.UserBankInfo) == 0 {
		return &types.UserBankInfoResponse{
			UserBankInfo: infos,
		}, nil
	}

	for _, bankInfo := range info.GetUserBankInfo() {
		infos = append(infos, &types.UserBankInfo{
			ID:         bankInfo.Id,
			UserName:   bankInfo.UserName,
			CardNum:    bankInfo.CardNumber,
			Email:      bankInfo.Email,
			Phone:      bankInfo.Phone,
			BankName:   bankInfo.BankName,
			Province:   bankInfo.Province,
			City:       bankInfo.City,
			IFSCCode:   bankInfo.IfscCode,
			BranchBank: bankInfo.BranchBank,
			BankId:     bankInfo.BankId,
		})
	}

	return &types.UserBankInfoResponse{
		UserBankInfo: infos,
	}, nil
}
